package handledb;

import com.fasterxml.jackson.annotation.JsonFormat;
import handledb.annotaions.*;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * 对实体类进行处理
 * 默认处理规则：类名及表面、类属性名你及表格对应的字段名、第一个字段默认为主键  （可驼峰命名）；所有属性都是对应数据库表的字段
 * NotUpdateFiled、FiledRelation、Condition、In  注解的属性不是表格里面的字段  创建跟新数据的时候不会使用这些注解的字段
 * Primary 注解的字段表示为主键
 * RowName 可以自定义字段名、主键
 * Table 可以自定义表名、主键
 * FieldRelation 注解用于单表关联查询的时候查询关联字段
 * Condition 注解用于辅助查询的条件
 * In 注解用于in()语句
 */
public class ClassInfo {
    public FieldInfo[] allFieldInfos;
    public String tableName;
    public Constructor con = null;
    public String beanName = null;

    // 将驼峰命名的字段修改为下划线分隔符的字符串
    public static String dealFiledName(String name) {
        char[] strs = name.toCharArray();
        int k = 0;
        int n = 0;
        for (char s : strs) {
            if ('A' <= s && s <= 'Z') {
                if (n != 0) {
                    k++;
                }
            }
            n++;
        }
        char[] newStrs = new char[strs.length + k];
        k = 0;
        for (int i = 0; i < strs.length; i++) {
            if ('A' <= strs[i] && strs[i] <= 'Z') {
                if (i != 0) {
                    newStrs[k++] = '_';
                }
                strs[i] += 32;
            }
            newStrs[k++] = strs[i];
        }
        return new String(newStrs);
    }

    // 时间处理
    public static void dealDateFormat(FieldInfo fieldInfo, Field field) {
        JsonFormat jsonFormat = field.getAnnotation(JsonFormat.class);
        String format = "YYYY-MM-dd";
        String oracleFormat = "";
        String mysqlFormat = "";
        if (jsonFormat != null) {
            format = jsonFormat.pattern();
        } else {
            DateFormat dateFormat = field.getAnnotation(DateFormat.class);
            if (dateFormat != null) {
                format = dateFormat.value();
            }
        }
        if (format == null || "".equals(format)) {
            format = "YYYY-MM-dd";
        }
        oracleFormat = format;
        String[] arrs = format.split(" ");
        if (arrs.length == 2) {
            String[] strs = arrs[1].split(":");
            if (strs.length > 1) {
                for (int k = 0; k < strs.length; k++) {
                    if ("mm".equals(strs[k])) {
                        strs[k] = "mi";
                    } else if ("HH".equals(strs[k])) {
                        strs[k] = "hh24";
                    }
                }
            }
            oracleFormat = arrs[0] + " " + String.join(":", strs);
        }
        boolean hasE = false;
        char connector = '-';
        if (format.indexOf('/') > -1) {
            connector = '/';
        }
        if (format.indexOf('Y') > -1) {
            mysqlFormat += "%Y";
            hasE = true;
        } else if (format.indexOf('y') > -1) {
            mysqlFormat += "%Y";
            hasE = true;
        } else {
            hasE = false;
        }
        if (format.indexOf('M') > -1) {
            if (hasE) mysqlFormat += connector;
            mysqlFormat += "%m";
            hasE = true;
        } else {
            hasE = false;
        }
        if (format.indexOf('d') > -1) {
            if (hasE) mysqlFormat += connector;
            mysqlFormat += "%d";
            hasE = true;
        } else {
            hasE = false;
        }
        if (format.indexOf('H') > -1) {
            if (hasE) mysqlFormat += ' ';
            mysqlFormat += "%H";
            hasE = true;
        } else if (format.indexOf('h') > -1) {
            if (hasE) mysqlFormat += ' ';
            mysqlFormat += "%h";
            hasE = true;
        } else {
            hasE = false;
        }
        if (format.indexOf('m') > -1) {
            if (hasE) mysqlFormat += ':';
            mysqlFormat += "%i";
            hasE = true;
        } else {
            hasE = false;
        }
        if (format.indexOf('s') > -1) {
            if (hasE) mysqlFormat += ':';
            mysqlFormat += "%s";
        }
        fieldInfo.format = format;
        fieldInfo.oracleFormat = oracleFormat;
        fieldInfo.mysqlFormat = mysqlFormat;
    }

    public ClassInfo(Class c) {
        this.beanName = c.getSimpleName();
        try {
            con = c.getConstructor();
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
        RowName rn = null;
        Condition condition = null;
        FieldRelation fieldRelation = null;
        NotUpdateField notUpdateField = null;
        Primary primary = null;
        Like like = null;
        In in = null;
        String conditionStr;
        FieldInfo fieldInfo;
        String primaryField = null;
        int primaryFieldIndex = -1;
        String typeName = null;
        int fieldLength = 0;
        List<FieldInfo[]> infos = new ArrayList<>();
        Field[] fs = null;
        while (!c.getSimpleName().equals("Object")) {
            fs = c.getDeclaredFields();
            int i = 0;
            Table table = (Table) c.getAnnotation(Table.class);
            if (table != null) {
                tableName = table.name();
                primaryField = table.primary();
            } else {
                tableName = dealFiledName(c.getSimpleName());
            }
            FieldInfo[] fInfos = new FieldInfo[fs.length];
            for (Field field : fs) {
                fieldInfo = fInfos[i] = new FieldInfo();
                fieldInfo.field = field;
                fieldInfo.name = field.getName();
                field.setAccessible(true);
                rn = field.getAnnotation(RowName.class);
                if (rn != null) {
                    fieldInfo.columnName = rn.value();
                    if (rn.primary()) {
                        primaryFieldIndex = fieldLength + i;
                    }
                }
                primary = field.getAnnotation(Primary.class);
                if (primary != null) {
                    String pstr = primary.value();
                    if (fieldInfo.columnName == null && !pstr.equals("")) {
                        fieldInfo.columnName = pstr;
                    }
                    primaryFieldIndex = fieldLength + i;
                }
                if (fieldInfo.columnName == null) {
                    fieldInfo.columnName = dealFiledName(fieldInfo.name);
                }
                // 确定主键的位置
                if (primaryFieldIndex < 0 && fieldInfo.columnName.equals(primaryField)) {
                    primaryFieldIndex = fieldLength + i;
                }
                condition = field.getAnnotation(Condition.class);
                if (condition != null) {
                    conditionStr = condition.value();
                    if (conditionStr.indexOf(" and ") > -1 || conditionStr.indexOf(" or ") > -1) {
                        fieldInfo.conditionSql = conditionStr;
                    } else {
                        fieldInfo.conditionSql = " and " + conditionStr;
                    }
                    fieldInfo.updateField = condition.updateField();
                }
                fieldRelation = field.getAnnotation(FieldRelation.class);
                if (fieldRelation != null) {
                    fieldInfo.updateField = false;
                    fieldInfo.relationSql = "(" + fieldRelation.value() + ") as " + fieldInfo.columnName;
                }
                notUpdateField = field.getAnnotation(NotUpdateField.class);
                if (notUpdateField != null) {
                    fieldInfo.updateField = false;
                }
                like = field.getAnnotation(Like.class);
                if (like != null) {
                    fieldInfo.like = like.value();
                    fieldInfo.updateField = like.updateField();
                }
                in = field.getAnnotation(In.class);
                if (in != null) {
                    conditionStr = in.value();
                    if (conditionStr.indexOf(" and ") > -1 || conditionStr.indexOf(" or ") > -1) {
                        fieldInfo.conditionSql = conditionStr;
                    } else {
                        fieldInfo.conditionSql = " and " + conditionStr;
                    }
                    fieldInfo.updateField = false;
                }
                typeName = field.getType().getTypeName();
                switch (typeName) {
                    case "java.lang.String":
                        fieldInfo.type = 1;
                        break;
                    case "java.lang.Integer":
                        fieldInfo.type = 2;
                        break;
                    case "java.lang.Long":
                        fieldInfo.type = 3;
                        break;
                    case "java.util.Date": {
                        fieldInfo.type = 4;
                        dealDateFormat(fieldInfo, field);
                    }
                    break;
                    case "java.lang.Double":
                        fieldInfo.type = 5;
                        break;
                    case "java.lang.Float":
                        fieldInfo.type = 6;
                        break;
                    case "java.lang.Short":
                        fieldInfo.type = 7;
                        break;
                    case "java.lang.Character":
                        fieldInfo.type = 8;
                        break;
                    case "java.lang.Integer[]":
                        fieldInfo.type = 20;
                        break;
                    case "java.lang.String[]":
                        fieldInfo.type = 21;
                        break;
                    case "java.lang.Long[]":
                        fieldInfo.type = 22;
                        break;
                    case "java.lang.Double[]":
                        fieldInfo.type = 23;
                        break;
                    case "java.lang.Float[]":
                        fieldInfo.type = 24;
                        break;
                    case "java.lang.Short[]":
                        fieldInfo.type = 25;
                        break;
                    default:
                        fieldInfo.type = 100;    // 数组List
                }
                i++;
            }
            fieldLength += i;
            if (fs.length > 0) {
                infos.add(fInfos);
            }
            c = c.getSuperclass();
            if (c == null) {
                break;
            }
        }
        if (infos.size() < 1) {
            allFieldInfos = infos.get(0);
        } else {
            allFieldInfos = new FieldInfo[fieldLength];
            int i = 0;
            for (FieldInfo[] arr : infos) {
                for (FieldInfo item : arr) {
                    allFieldInfos[i] = item;
                    i += 1;
                }
            }
        }
        if (primaryFieldIndex > 0) {
            fieldInfo = allFieldInfos[primaryFieldIndex];
            allFieldInfos[primaryFieldIndex] = allFieldInfos[0];
            allFieldInfos[0] = fieldInfo;
        }
    }
}
